package com.zhangliang.utils;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class ValueItem {
    private long time;  // 值所在的时刻
    private int value;

    public ValueItem(long time, int value) {
        this.time = time;
        this.value = value;
    }

    public long getTime() {
        return time;
    }

    public int getValue() {
        return value;
    }

}


public class TPMonitor {
    private int interval;
    private List<ValueItem> valueList = new ArrayList<>();

    // interval秒内的TP监控
    public TPMonitor(int interval) {
        this.interval = interval;
    }

    // 获取percent对应的TP
    public int getTopPercentile(double percent) {
        assert (percent >= 0 && percent <= 100);


        // 去除超过监控时间外的统计元素
        long now = System.currentTimeMillis();
        Iterator<ValueItem> iterator = valueList.iterator();
        while (iterator.hasNext()) {
            ValueItem valueItem = iterator.next();
            if (valueItem.getTime() <= now - interval * 1000) {
                iterator.remove();
            } else {
                break;
            }
        }

        // 将数字去除并排序，返回对应的TP
        List<Integer> intList = new ArrayList<>();
        for (ValueItem valueItem : valueList) {
            intList.add(valueItem.getValue());
        }

        intList.sort((num1, num2)-> {
            return num1 - num2;
        });

        int index = (int)Math.ceil(intList.size() * percent / 100);
        if (index <= 0) {
            return 0;
        }

        return intList.get(index - 1);

    }

    // 添加新的值
    public void offer(int value) {
        valueList.add(new ValueItem(System.currentTimeMillis(), value));
    }


}
